/*
 * $Id: JavaUnixSys.java 3 2007-12-07 01:24:30Z rasan.rasch $
 *
 * Copyright (c) 2002-2006 UC Regents
 * 
 * Permission to use, copy, modify, distribute, and sell this software and
 * its documentation for any purpose is hereby granted without fee, provided
 * that (i) the above copyright notices and this permission notice appear in
 * all copies of the software and related documentation, and (ii) the names
 * of the UC Regents and the University of California are not used in any
 * advertising or publicity relating to the software without the specific,
 * prior written permission of the University of California.
 * 
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
 * 
 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY
 * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY
 * THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE
 * OR PERFORMANCE OF THIS SOFTWARE.
 */

package org.cdl.noid;

import jargs.gnu.CmdLineParser;
import javaunix.*;
import javaunix.io.*;
import java.io.IOException;

/** 
 * JavaUnixSys is a class for file system operations on a Unix-flavored
 * operating system.  It is a concrete class of the Sys abstract
 * class.  This class depends on the JavaUnix library available
 * at http://www.xenonsoft.demon.co.uk/products/javaunix/index.html
 * 
 * @author  Rasan Rasch (rasan@nyu.edu)
 * @version $Revision: 3 $
 */
public class JavaUnixSys extends Sys {

	/** 
	 * Construct a new JavaUnixSys object.
	 */
	public JavaUnixSys() {
		super();
	}

	/** 
	 * Return <code>CmdLineOptions</code> object representing the
	 * parsed command line options for <code>NoidTest<code>.
	 * 
	 * @param  args command line arguments
	 * @return      Options
	 * @see         Options
	 */
	public Options getOptions(String[] args) {
		CmdLineOptions opts = new CmdLineOptions(args);
		opts.parseOptions();
		return opts;
	}

	/** 
	 * Return string representing user for current process.
	 * 
	 * @param  isWeb is current process in web context
	 * @return       user string
	 */
	public String getUser(boolean isWeb) {
	
		String user = null;

		if (isWeb) {
			user = System.getenv("REMOTE_USER");
			String host = System.getenv("REMOTE_HOST");
			if (host == null)
				host = System.getenv("REMOTE_ADDR");
			user += '@' + host;
		}
		
		try {
			int uid = UnixSystem.getUid();
			int gid = UnixSystem.getGid();
			int effectiveUid = UnixSystem.getEffectiveUid();
			int effectiveGid = UnixSystem.getEffectiveGid();
	
			Password passwd = UnixSystem.getPasswordByUid(uid);
			Group group = UnixSystem.getGroupByGid(gid);
		
			String userName = System.getProperty("user.name");
			if (userName == null)
				userName = passwd.getName();
			if (userName == null)
				return "";
		
			String groupName = group.getName();
			user = userName + "/" + Util.valueOrEmpty(groupName);

			if (uid != effectiveUid) {
				passwd = UnixSystem.getPasswordByUid(uid);
				group = UnixSystem.getGroupByGid(gid);
				userName = passwd.getName();
				if (userName == null)
					return "";
				groupName = group.getName();
				user += " (" + userName + "/"
					+ Util.valueOrEmpty(groupName) + ")";
			}
		} catch (Exception e) {
			System.err.println(e);
		}

		return user;
	
	}

	/** 
	 * Set permissions for a file.
	 * 
	 * @param fileName input file whose mode will be changed
	 * @return         <code>true</code> if operation was successful;
	 *                 <code>false</code> otherwise
	 */
	public boolean chmod(String fileName) {
		UnixFile file = new UnixFile(fileName);
		return file.setMode(0600);
	}

	/** 
	 * Print system information to stdout.
	 */
	public static void printSystemInfo() {
		System.out.print( "\n\n");
		System.out.println( "*********************************************" );
		System.out.println( "* System Provider Test I                    *" );
		System.out.println( "*********************************************\n" );
	
		System.out.println( "getUid() = "+UnixSystem.getUid() );
		System.out.println( "getGid() = "+UnixSystem.getGid() );
		System.out.println( "getPid() = "+UnixSystem.getPid() );
		System.out.println( "getParentPid() = "+UnixSystem.getParentPid() );
		System.out.println( "getEffectiveUid() = "+UnixSystem.getEffectiveUid() );
		System.out.println( "getEffectiveGid() = "+UnixSystem.getEffectiveGid() );

		int umask = UnixSystem.getUmask((short)0);
		System.out.println( "getUmask(0) = 0"+Integer.toOctalString(umask) );

		try {
			System.out.println("\nUsing ``UnixSystem.setUid(0)'' to become root." );
			if ( System.getProperty("user.name").equals("root") )
			System.out.println("I am `root' so it should work WITHOUT exception." );
			else
			System.out.println("I am NOT currently `root' so it should fail WITH exception." );
			UnixSystem.setUid(0);
		}
		catch ( UnixSystemException use ) {
			System.err.println( "Exception:"+use.getMessage() );
		}
    }

}
